package net.huashitong.ssydt.provider.alipay.service;


import net.huashitong.ssydt.money.constant.MoneyConsts;
import net.huashitong.ssydt.money.entity.SsMoneyOrder;
import net.huashitong.ssydt.provider.alipay.entity.NotifyModel;
import net.huashitong.ssydt.provider.money.service.MoneyService;
import net.huashitong.ssydt.provider.money.service.SsMoneyOrderService;
import net.huashitong.ssydt.provider.utils.date.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author <a href="mailto:yhy23456@163.com">huiyang.yu</a>
 * @since 2017.08.18
 */
@Service
@Transactional
public class AlipaySuccessServiceImpl implements AlipaySuccessService {

    private Logger logger = LoggerFactory.getLogger(AlipaySuccessServiceImpl.class);

    private SsMoneyOrderService ssMoneyOrderService;

    private MoneyService moneyService;

    @Autowired
    public AlipaySuccessServiceImpl( SsMoneyOrderService ssMoneyOrderService,
                                     MoneyService moneyService) {
        this.ssMoneyOrderService = ssMoneyOrderService;
        this.moneyService = moneyService;
    }

    @Override
    public void paySuccess(NotifyModel model) {
        SsMoneyOrder ssMoneyOrder = this.ssMoneyOrderService.getByOrderId(model.getOut_trade_no());
        if (ssMoneyOrder == null) {
            logger.info("支付宝订单号 [{}] 支付金额 [￥{}] 商户订单号 [{}] ,在系统中不存在",
                    model.getTrade_no(), model.getTotal_amount(), model.getOut_trade_no());
            return;
        }
        //防止重复处理订单
        if (MoneyConsts.OrderState.PAID.equals(ssMoneyOrder.getOrderState())){
            return;
        }
        ssMoneyOrder.setPayType(MoneyConsts.PayType.ALI_PAY);
        ssMoneyOrder.setPayAccount(model.getBuyer_logon_id());
        ssMoneyOrder.setPayOrderId(model.getTrade_no());
        ssMoneyOrder.setGmtPay(DateUtils.parseDate(model.getGmt_payment()));
        ssMoneyOrder.setOrderState(MoneyConsts.OrderState.PAID);
        ssMoneyOrderService.update(ssMoneyOrder);
        moneyService.payCallback(ssMoneyOrder);//支付回调

    }
}
